﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Web.Security;
using System.Security.Principal;

/// <summary>
/// This is a class for common webserver operations.
/// </summary>
public class WebCommon
{
    /// <summary>
    /// Initializes a new instance of the <see cref="WebCommon"/> class.
    /// </summary>
    public WebCommon() { }

    /// <summary>
    /// Creates a new instance of <see cref="SqlConnection"/> class and open it.
    /// </summary>
    /// <returns>A new and opened instance of <see cref="SqlConnection"/> class.</returns>
    public static SqlConnection CreateConnection()
    {
        string connectionString = string.Format(@"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;User Instance=True",
            HttpContext.Current.Server.MapPath("~/App_Data/Database.mdf"));

        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = connectionString;
        connection.Open();

        return connection;
    }

    /// <summary>
    /// Authenticates the web request.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    public static void AuthenticateRequest(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;
        if (app != null)
        {
            HttpCookie authCookie = app.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value))
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                app.Context.User = new GenericPrincipal(new GenericIdentity(ticket.Name, "Custom"), new string[0]);
            }
        }
    }
}
